<template>
  <div id="categoryPage">
    <!-- 使用麵包屑組件 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <TableFilter :config="filterConfig" @search="handleSearch" />
    <!-- 工具欄 -->
    <a-space>
      <a-button type="primary" @click="handleCreate">
        <template #icon>
          <PlusOutlined />
        </template>
        新建
      </a-button>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
      >
        <!-- 表格頭部 -->
        <template #headerCell="{ column }">
          <!-- 根據表頭字段進行表頭修飾 -->
        </template>

        <!-- 表格內容 -->
        <template #bodyCell="{ column, record }">
          <!-- 根據不同的列顯示不同的內容修飾 -->
          <template v-if="column.dataIndex === 'updatedBy'">
            {{ record.updatedBy?.username ?? "" }}
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleEdit(record)">修改</a-button>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 新建模態框 -->
    <a-modal v-model:open="showModalCreate" title="新建業務大類" :footer="null">
      <DynamicForm
        ref="createFormRef"
        :fieldConfig="createFieldConfig"
        @submit="handleCreateSubmit"
      />
    </a-modal>
    <!-- 修改模態框 -->
    <a-modal v-model:open="showModalEdit" title="修改業務大類" :footer="null">
      <a-alert
        type="info"
        :message="`當前編輯業務大類ID: ${editFormData.id}`"
        show-icon
      />
      <DynamicForm
        ref="editFormRef"
        :fieldConfig="editFieldConfig"
        :formData="editFormData"
        @submit="handleEditSubmit"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { message, Modal } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { categoryApi } from "@/api";
import DynamicForm from "@/components/DynamicForm.vue";
import {
  tableColumns,
  filterFields,
  getCreateFieldConfig,
  getEditFieldConfig,
} from "@/models/category";
import TableFilter from "@/components/TableFilter.vue";
import { useRouter, useRoute } from "vue-router";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import { createPagination } from "@/utils/pagination";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";

/*******頁面狀態與配置 *****************************/
const breadcrumbItems = [{ url: "", name: "業務大類管理" }];
const columns = tableColumns;
const filterConfig = filterFields;
const createFieldConfig = ref<Record<string, any>>({});
const editFieldConfig = ref<Record<string, any>>({});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
// 分頁配置
const pagination = createPagination();

// 數據
const tableData = ref([]);
const editRecordId = ref<number>(0); // 當前編輯的用戶ID
const editFormData = reactive<any>({}); // 當前編輯的用戶數據

/******* 數據獲取與初始化 *****************************/

// 獲取數據
const fetchData = async (params?: any) => {
  loading.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await categoryApi.getCategoryList(params);
    tableData.value = list || [];
    // 更新分頁參數
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取業務大類列表失敗", error);
  } finally {
    loading.value = false; // 結束加載
  }
};
// 頁面加載時初始化數據
watchRouteQuery(fetchData);

/******* 用戶操作處理 *****************************/
// 搜索
const handleSearch = (params: any) => {
  router.push({ query: params });
};

// 新建
const showModalCreate = ref(false);

const handleCreate = () => {
  if (Object.keys(createFieldConfig.value).length === 0) {
    createFieldConfig.value = getCreateFieldConfig();
  }
  showModalCreate.value = true;
};

const createFormRef = ref();
const handleCreateSubmit = async (data: any) => {
  // 處理表單提交邏輯
  try {
    await categoryApi.createCategory(data);
    message.success("創建業務大類成功");
    showModalCreate.value = false;
    // 調用子組件的 resetForm 方法
    createFormRef.value?.resetForm();
    fetchData(route.query);
  } catch (error) {
    console.error("創建業務大類失敗", error);
  } finally {
    createFormRef.value?.resetLoading();
  }
};

// 修改
const showModalEdit = ref(false);

const handleEdit = (record: any) => {
  if (Object.keys(editFieldConfig.value).length === 0) {
    editFieldConfig.value = getEditFieldConfig();
  }
  editRecordId.value = Number(record.id);
  Object.assign(editFormData, record); // 使用 Object.assign 更新 reactive 對象
  showModalEdit.value = true;
};
// 處理編輯完成
const editFormRef = ref();
const handleEditSubmit = async (data: any) => {
  try {
    await categoryApi.updateCategory(editRecordId.value, data);
    message.success("修改業務大類成功");
    showModalEdit.value = false;
    fetchData(route.query);
  } catch (error) {
    console.error("修改業務大類失敗", error);
  } finally {
    editFormRef.value?.resetLoading();
  }
};
</script>

<style scoped></style>
